﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Gift.DAL.crm;
using Gift.Model.crm;
using Gift.Model.crm.eNum;
using Gift.DAL;
using Gift.Model;

namespace WebSite.crm.company
{
    public partial class companyAdd :  BaseCrm
    {
        readonly t_DALCompany  theCompany = new t_DALCompany();
        readonly adminlogin theAdminLogin = new adminlogin();
        readonly t_DALUserRuleRef theUserRuleRef = new t_DALUserRuleRef();
        readonly t_DALRule theRule = new t_DALRule();
        readonly t_DALRegion theRegion = new t_DALRegion();
        public int ParaCompanyId
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    return -1;
                }
                else
                {
                    return int.Parse(Request.QueryString["id"]);
                }
            }
        }
        public string Action
        {
            get
            {
                return Request.QueryString["action"];

            }
        }

        string ParamentType
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["type"]))
                {
                    return string.Empty;
                }
                else
                {
                    return Request.QueryString["type"];
                }
            }
        }


        public void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
              

                base.ValidateLoginRule(eRule.CompanyAdd);

                if (ParaCompanyId > -1 )
                {
                    this.txtName.Enabled = false;
                    this.txtShortName.Enabled = false;
                    this.txtCompanyCode.Enabled = false;
                    this.txtManager.Enabled = false;
                    this.txtManagerMobile.Enabled = false;
                    this.ddlSheng.Enabled = false;
                    this.ddlShi.Enabled = false;
                    this.txtAddress.Enabled = false;
                    this.ddlCompanyLevel.Enabled = false;
                    t_Company oCompany = theCompany.GetModel(ParaCompanyId);
                    if (string.IsNullOrEmpty(base.CompanyId))
                    {
                        this.txtOnSale.Enabled = true;
                        this.txtCreditMoney.Enabled = true;
                    }
                    else
                    {
                        this.txtOnSale.Enabled = false;
                        this.txtCreditMoney.Enabled = false;
                    }

                }
                this.BindCompanyLevel();
                this.BindPrivence();
                this.BindCity();
                this.BuildForm();


            }
        }


        protected void chk1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chk1.Checked)
            {
                this.txtLinker.Text = this.txtManager.Text;
                this.txtMobile.Text = this.txtManagerMobile.Text;
            }

        }

        void BuildForm()
        {
            if (Action == "del")
            {
                if (base.CompanyId != null)
                {
                    ExtAspNet.Alert.Show("不能删除自己！");
                    base.Response.End();
                }
                else
                {
                   
                theCompany.Delete(ParaCompanyId);
                ExtAspNet.Alert.Show("删除成功！", "", "window.location.href='companyManager.aspx';");
                base.Response.End();
                  
                }
            }

            else if (ParaCompanyId >= 0)
            {
                t_Company oCompany;
                oCompany = theCompany.GetModel(ParaCompanyId);
                if (theCompany != null)
                {
                    if (base.CompanyId != null)
                    {
                        this.txtAddress.Text = oCompany.Provence + "," + oCompany.Area + "," + oCompany.Address;
                    }
                    else
                    {
                        this.txtAddress.Text = oCompany.Address;
                    }
                    this.txtEmail.Text = oCompany.Email;
                    this.txtFax.Text = oCompany.Fax;
                    this.txtLinker.Text = oCompany.Linker;
                    this.txtName.Text = oCompany.Name;
                    this.hdCompany.Text = oCompany.Name;
                    this.txtPostcode.Text = oCompany.Postcode;
                    this.txtQQ.Text = oCompany.QQ;
                    this.txtTel.Text = oCompany.Telephone;
                    this.ddlCompanyCategory.Items.FindByValue(oCompany.CompanyTypeId.ToString()).Selected = true;
                    if (oCompany.LevelId == 0)
                    {
                        this.ddlCompanyLevel.Items.Insert(0, new ExtAspNet.ListItem("顶级", "0"));
                    }
                    this.ddlCompanyLevel.Items.FindByValue(oCompany.LevelId.ToString()).Selected = true;

                    this.txtOnSale.Text = theCompany.GetCompanyOnSale(oCompany.Id.ToString()).ToString();
                    this.txtCreditMoney.Text = oCompany.CreditMoney.ToString();
                    this.txtMobile.Text = oCompany.Mobile;
                    this.txtCompanyCode.Text = oCompany.CompanyCode;
                    this.txtShortName.Text = oCompany.CompanyShortName;
                    this.txtManager.Text = oCompany.CompanyManager;
                    this.txtManagerMobile.Text = oCompany.CompanyManagerMobile;

 


                    if (base.CompanyId != null)
                    {
                        this.ddlCompanyLevel.Enabled = false;
                        this.txtOnSale.Enabled = false;
                        this.txtUserName.Text = base.AdminUser;

                    }
                    else
                    {
                        this.txtPassword.Hidden = true;
                        this.txtUserName.Hidden = true;
                        this.txtUserName.Required = false;
                        this.txtPassword.Required = false;
                    }
                
                    if (this.ddlSheng.Items.FindByText(oCompany.Provence) != null)
                    {
                        this.ddlSheng.SelectedValue = this.ddlSheng.Items.FindByText(oCompany.Provence).Value;
                        this.BindCity();
                    }
                    if (this.ddlShi.Items.FindByText(oCompany.City) != null)
                    {
                        this.ddlShi.SelectedValue = this.ddlShi.Items.FindByText(oCompany.City).Value;
                    }
      
                    this.txtUserName.Enabled = false;

                }
            }
            else
            {
                this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode().ToString();
            }
        }

        protected void btnSubmitForm1_Click(object sender, EventArgs e)
        {
            t_Company oCompany;
            DB_adminlogin  oAdminLogin;
            oCompany = null;
            if (ParaCompanyId > -1)
            {
                oCompany = theCompany.GetModel(ParaCompanyId);
            }

            if (oCompany == null) oCompany = new t_Company();

            try
            {
                double dSale = double.Parse(this.txtOnSale.Text.Trim());
                if ((dSale < 0.5 || dSale > 1.0) && base.CompanyLevelId != "0" && base.CompanyLevelId != "1")
                {
                    ExtAspNet.Alert.Show("折扣只能为0.50-1.00的数字！");
                    return;
                }
                else if (dSale < 0.2 || dSale > 1.0)
                {
                    ExtAspNet.Alert.Show("折扣只能为0.20-1.00的数字！");
                    return;
                }
            }
            catch
            {
                ExtAspNet.Alert.Show("折扣只能为0.50-1.00的数字！");
                return;
            }

            try
            {
                double dCreditMoney = double.Parse(this.txtCreditMoney.Text.Trim());
                if (dCreditMoney < 0)
                {
                    ExtAspNet.Alert.Show("授信额度只能为大于等于0的数字！");
                    return;
                }
            }
            catch
            {
                ExtAspNet.Alert.Show("授信额度只能为大于等于0的数字！");
                return;
            }
            oCompany.Id = ParaCompanyId;
            oCompany.Email = this.txtEmail.Text.Trim();
            oCompany.Linker = this.txtLinker.Text.Trim();
            oCompany.Fax = this.txtFax.Text.Trim();
            oCompany.Name = this.txtName.Text.Trim();
            oCompany.Postcode = this.txtPostcode.Text.Trim();
            oCompany.QQ = this.txtQQ.Text.Trim();
            oCompany.Telephone = this.txtTel.Text.Trim();
      
                oCompany.ParentId = 0;
   
            oCompany.LevelId = int.Parse(this.ddlCompanyLevel.SelectedItem.Value);
            oCompany.Mobile = this.txtMobile.Text.Trim();
            oCompany.CompanyTypeId = int.Parse(this.ddlCompanyCategory.SelectedItem.Value);
            oCompany.CompanyCode = this.txtCompanyCode.Text.Trim();
            oCompany.CompanyShortName = this.txtShortName.Text.Trim();
            oCompany.CompanyManager = this.txtManager.Text.Trim();
            oCompany.CompanyManagerMobile = this.txtManagerMobile.Text.Trim();
            oCompany.CreditMoney = this.txtCreditMoney.Text.Trim() == "" ? 0 : decimal.Parse(this.txtCreditMoney.Text);
            oCompany.Provence = this.ddlSheng.SelectedItem.Text;
            oCompany.City = this.ddlShi.SelectedItem.Text;

            oCompany.Address = this.txtAddress.Text.Trim();
            try
            {
                if (ParaCompanyId >= 0)
                {
                    if (theCompany.ExistsByCode(this.txtCompanyCode.Text.Trim()) && oCompany.CompanyCode != this.txtCompanyCode.Text.Trim())
                    {
                        ExtAspNet.Alert.Show("系统中已有此公司编码，请重新设置编码！");
                        this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode().ToString();
                        return;
                    }

                    if (this.hdCompany.Text != oCompany.Name)
                    {
                        t_Company tempCompany = theCompany.GetModelByName(oCompany.Name);
                        if (tempCompany != null)
                        {
                            ExtAspNet.Alert.Show("该公司名已存在,请重新输入公司名！");
                            return;
                        }
                    }
                    if (oCompany.CompanyShortName != this.txtShortName.Text.Trim()
                         && theCompany.ExistsByShortName(this.txtShortName.Text.Trim()))
                    {
                        ExtAspNet.Alert.Show("该公司简称已存在,请重新输入公司简称！");
                        return;
                    }

             
                    oAdminLogin = new DB_adminlogin();
                    if (base.CompanyId == ParaCompanyId.ToString())
                    {
                        int iAdminId = theAdminLogin.GetIdByName(this.txtUserName.Text.Trim());

                        if (iAdminId <= 0)
                        {
                            oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                            oAdminLogin.AdminPwd =  System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                            iAdminId = theAdminLogin.Add(oAdminLogin);
                            oAdminLogin.AdminId = iAdminId;
                        }
                        else
                        {
                            oAdminLogin.AdminId = iAdminId;
                            oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                            if (!string.IsNullOrEmpty(this.txtPassword.Text.Trim()))
                            {
                                oAdminLogin.AdminPwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                                theAdminLogin.Update(oAdminLogin);
                            }
                        }
                    }
                    theCompany.Update(oCompany);
                    theCompany.IsExistsOnSale(oCompany.Id.ToString(), float.Parse(this.txtOnSale.Text.Trim()));
                }
                else
                {
                    oCompany.Provence = this.ddlSheng.SelectedItem.Value;

                    oCompany.Area = this.ddlShi.SelectedItem.Value;
                    oCompany.Address = this.txtAddress.Text.Trim();

                    t_Company tempCompany = theCompany.GetModelByName(oCompany.Name);
                    if (tempCompany != null)
                    {
                        ExtAspNet.Alert.Show("该公司名已存在,请重新输入公司名！");
                        return;
                    }

                    if (theCompany.ExistsByShortName(this.txtShortName.Text.Trim()))
                    {
                        ExtAspNet.Alert.Show("该公司简称已存在,请重新输入公司简称！");
                        return;
                    }

                    if (theCompany.ExistsByCode(this.txtCompanyCode.Text.Trim()))
                    {
                        ExtAspNet.Alert.Show("系统中已有此公司编码，请重新设置编码！");
                        this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode().ToString();
                        return;
                    }
                    oAdminLogin = new DB_adminlogin();

                    int iAdminId = theAdminLogin.GetIdByName(this.txtUserName.Text.Trim());
                    if (iAdminId > 0)
                    {
                        ExtAspNet.Alert.Show("该用户名已存在,请重新输入用户名！");
                        return;
                    }

                    if (this.txtPassword.Text.Trim() == "")
                    {
                        ExtAspNet.Alert.Show("密码不能为空！");
                        return;
                    }
                    oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                    oAdminLogin.AdminPwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                    iAdminId = theAdminLogin.Add(oAdminLogin);
                    theCompany.Add(oCompany);
                
                    oCompany = theCompany.GetModelByName(oCompany.Name);
                    SQLAccess.DoSql(string.Format("insert into t_CompanyAdmin(CompanyId,AdminId) values({0},{1});"
                                    , oCompany.Id, iAdminId.ToString()));
                    theCompany.IsExistsOnSale(oCompany.Id.ToString(), float.Parse(this.txtOnSale.Text.Trim()));
                }

 

                    ExtAspNet.Alert.Show("保存成功！", "", "openNewTab('CompanyManager','/crm/company/CompanyManager.aspx','公司管理','CompanyAdd')");

       

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
        }



        void BindCompanyLevel()
        {
            DataSet ds = theCompany.GetListForCompanyLevel();
            this.ddlCompanyLevel.DataTextField = "LevelName";
            this.ddlCompanyLevel.DataValueField = "Id";
        

                this.ddlCompanyLevel.DataSource = ds.Tables[0].DefaultView;
                this.ddlCompanyLevel.DataBind();
        }

  


        private void BindPrivence()
        {
            this.ddlSheng.Items.Clear();
            DataTable dtPrivence = theRegion.GetRegionByParentRegion(0);
            ddlSheng.DataTextField = "regionName";
            ddlSheng.DataValueField = "id";
            ddlSheng.DataSource = dtPrivence;
            ddlSheng.DataBind();

            ddlSheng.Items.Insert(0, new ExtAspNet.ListItem("选择省份", "-1"));
        }

        private void BindCity()
        {
            string sheng = ddlSheng.SelectedValue;
            this.ddlShi.Items.Clear();
            if (sheng != "-1")
            {
                DataTable dtCity = theRegion.GetRegionByParentRegion(int.Parse(sheng));
                this.ddlShi.DataTextField = "regionName";
                this.ddlShi.DataValueField = "id";
                ddlShi.DataSource = dtCity;
                ddlShi.DataBind();
            }

            ddlShi.Items.Insert(0, new ExtAspNet.ListItem("选择地区市", "-1"));
        }



        protected void ddlSheng_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCity();
        }

 
 
        public string HeaderHtml
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"]) && Request.QueryString["id"] != "0")
                {

                    t_Company oCompany = theCompany.GetModel(int.Parse(Request.QueryString["id"]));

                    string sHead = string.Format(" <div  class=\"navgater\"><img src=\"../images/module.gif\" width=\"20\" height=\"22\" alt=\"\"/> "
                                              + " 公司名称：{0} "
                                              + " <a style=\" display:block; float:right;\" href=\"javascript:location.href='companyList.aspx?id={1}&type={2}';\" ><img src=\"../images/history.gif\" border=\"0\" /></a>"
                                              + " </div>"
                                              , oCompany.Name
                                              , oCompany.ParentId.ToString()
                                              , ParamentType);
                    return sHead;
                }
                return string.Empty;

            }


        }
    }
}